package com.zerox.controller;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.zerox.domain.TableVO;
import com.zerox.pojo.SysUser;
import com.zerox.service.SysUserService;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/tolist")
    public String toList(){
        return "list";
    }

    @GetMapping("/toadd")
    public String toAdd(){
        return "add";
    }

    // @RequestMapping(value = "/list",method = RequestMethod.GET)
    //    public String list(Model model, @RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Model model, Integer page, HttpServletResponse resp, Integer limit,String realName,Integer roleId) throws IOException {

        List<SysUser> list = sysUserService.list(page,limit,realName,roleId);

        int count = sysUserService.count(realName,roleId);

        TableVO tableVO = new TableVO(0, count, list, "");

        String json = JSON.toJSONString(tableVO);

        return json;
    }

    @GetMapping("/list2")
    public String list2(Map<String,Object> map, @RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(this);
        map.put("id",id);
        // 转发
        return "forward:tolist";
    }

    @GetMapping("/list1")
    public ModelAndView list1(@RequestParam(value = "ids",required = false,defaultValue = "0") Integer id){
        System.out.println(id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("list.jsp");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    // @RequestMapping(value = "/add",method = RequestMethod.POST)
    @PostMapping("/addUser")
    public String add(Model model, HttpServletRequest request, @Valid SysUser sysUser, BindingResult bindingResult, MultipartFile idPic, MultipartFile idPic2) throws IOException {

        if (bindingResult.hasErrors()){
            //处理错误
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors){
                model.addAttribute(fieldError.getField()+"Error"+fieldError.getDefaultMessage());
            }
            return "add";
        }

        if (idPic != null) {
            if (idPic.getSize() > 2000000) {
                model.addAttribute("idPicPath","文件不能超过2M");
                return "add";
            }

            String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

            if (".jpg.png".indexOf(suffix) == -1) {
                model.addAttribute("idPicPath","文件格式不正确，不能上传");
                return "add";
            }

            //指定文件存储的目录
            String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "upload";  // ?

            String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;

            File fileTo = new File(path+File.separator+fileName);
            System.out.println(path+File.separator+fileName);
            //如果文件不存在就创建
            if (!fileTo.exists()) {
                fileTo.mkdirs();
            }
            //核心代码,将文件存储到指定位置
            idPic.transferTo(fileTo);

            sysUser.setIdpicpath(fileName);
        }

        int add = sysUserService.add(sysUser);

        if (add > 0) {
            model.addAttribute("msg",true);
            return "redirect:tolist";
        }

        model.addAttribute("msg",false);

        return "add";
    }

    @GetMapping("/view/{userid}")
    public String view(Model model,@PathVariable("userid") Integer id){

        SysUser sysUser = sysUserService.selectById(id);

        model.addAttribute("sysUser",sysUser);

        return "view";
    }

    @GetMapping("/update/{userid}")
    public String viewupdate(Model model,@PathVariable("userid") Integer id){

        SysUser sysUser = sysUserService.selectById(id);


        model.addAttribute("birthday",new SimpleDateFormat("yyyy-MM-dd").format(sysUser.getBirthday()));

        model.addAttribute("sysUser",sysUser);

        return "update";
    }

    @PostMapping("/updateUser/{userid}")
    public String update(Model model,HttpServletRequest request,MultipartFile idPic,@Valid SysUser sysUser,BindingResult bindingResult,@PathVariable("userid") Integer id) throws IOException {

        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                model.addAttribute(fieldError.getField()+"Error"+fieldError.getDefaultMessage());
            }
            return "update";
        }

        if (idPic.getSize() > 200000) {
            model.addAttribute("idPicPath"+"文件不能超过2M");
            return "update";
        }

        //指定文件存储的目录
        String path = request.getSession().getServletContext().getRealPath("statics") + File.separator + "upload";  // ?
        String suffix = idPic.getOriginalFilename().substring(idPic.getOriginalFilename().lastIndexOf("."));

        String fileName = RandomUtils.nextInt(1000000) + "_pic" + suffix;

        File fileTo = new File(path+File.separator+fileName);
        System.out.println(path+File.separator+fileName);
        //如果文件不存在就创建
        if (!fileTo.exists()) {
            fileTo.mkdirs();
        }
        //核心代码,将文件存储到指定位置
        idPic.transferTo(fileTo);

        sysUser.setId(id);
        sysUser.setIdpicpath(fileName);

//        model.addAttribute("birthday",new SimpleDateFormat("yyyy-MM-dd").format(sysUser.getBirthday()));

        int update = sysUserService.update(sysUser);

        model.addAttribute("msg", update > 0);

        return "update";
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id){

        int result = sysUserService.delete(id);

        return result > 0 ? "1" : "0";
    }

    @GetMapping("/accountExists")
    @ResponseBody
    public String accountExists(String account){
        SysUser sysUser = sysUserService.selectByAccount(account);
        if (sysUser==null){
            return "0";
        }
        return "1";
    }

    @GetMapping(value = "/see/{id}",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String see(@PathVariable Integer id){

        SysUser sysUser = sysUserService.selectById(id);
        String string = JSON.toJSONString(sysUser);

        return string;
    }
}
